import userApi from '@/api/center/user'
import dictApi from '@/api/system/dict'
import { getToken } from '@/utils/auth'


export default {
  name:'data',
  
  
  data() {
    const validatePassword = (rule, value, callback) => {
      if (value.length < 6) {
        callback(new Error('密码不能小于6位'))
      } else {
        callback()
      }
    }
    const validateconfirmPassword = (rule, value, callback) => {
      if(value === ''){
        callback(new Error('请确认密码'))
      }else if ( value  != this.ResetForm.newPassword) {
        callback(new Error('两次密码不一致'))
      } else {
        callback()
      }
    }
    return {
      rules: {
        newPassword: [{ required: true, trigger: 'blur', validator: validatePassword }],
        confirmPassword: [{ validator: validateconfirmPassword, trigger: 'blur', required: true }]
      },
      
         UserInfo :{
            username: '',
            nickname: '',
            phone: '',
            sex: '',
            avatar: '',
            createTime: '',
          },
          RestInfo:{
            nickname: '',
            phone: '',
            email: '',
            sex: ''
          },
            ResetForm : {
            oldPassword: '',
            newPassword: '',
            confirmPassword: '',
          },
          sexDict:{},
          // 上传相关参数
        uploadParams: {
          uploadUrl: process.env.VUE_APP_BASE_API + "file/uploadAvatar",
          headers: {'logistics-token':getToken()}
        },
        avatar: '',
          
    }
  },
  filters: {
  },
  created() {
    this.init()
  },
  methods: {
    formatDate(originVal) {
      const dt = new Date(originVal);
      const y = dt.getFullYear();
      const m = (dt.getMonth() + 1 + "").padStart(2, "0");
      const d = (dt.getDate() + "").padStart(2, "0");
      const hh = (dt.getHours() + "").padStart(2, "0");
      const mm = (dt.getMinutes() + "").padStart(2, "0");
      const ss = (dt.getSeconds() + "").padStart(2, "0");
      return `${y}-${m}-${d} ${hh}:${mm}:${ss}`;
    },
    formatSex(num){
      return this.formatDict(this.sexDict,num)
    },
    formatDict(dict,num){
      if(dict){
      for(let i=0;i<dict.length;i++)
        if(dict[i].num==num){
          return dict[i].name
        }
      }
      return ''
     },
    init() {
      this.fetchData()
      this.getSexDict()
      
    },
    getAvatar(){
      fetch( process.env.VUE_APP_BASE_API + "file/getAvatar",{
        headers:{
        'logistics-token':getToken()}
      })
      .then(res => res.blob())
      .then(blob => {
        const reader = new FileReader();
        reader.onloadend = () => {
          this.avatar = reader.result; // 将Base64字符串设置给imageSrc
        };
        reader.readAsDataURL(blob);
      })
      .catch(error => console.error('Error fetching image:', error));
    },
    fetchData() {
      userApi.getProfile().then(response => {
        this.UserInfo = response.data
        Object.keys(this.RestInfo).forEach(key => {
          if (this.UserInfo.hasOwnProperty(key)) {
            this.RestInfo[key] = this.UserInfo[key];
          }
        });
        this.getAvatar()
      });
      
    },
    getSexDict(){
    // 从后台获取字典列表
    let dictName = '性别'
      dictApi.getDicts(dictName).then(response => {
        this.sexDict = response.data[0].children ?? []
      })
    },
    handleAvatarSuccess(res, file) {
      this.getAvatar()
    },
    beforeAvatarUpload(file) {
      const isType = file.type === 'image/jpeg' || 'image/png';
      const isLt4M = file.size / 1024 / 1024 < 4;

      if (!isType) {
        this.$message.error('上传头像图片只能是 JPG\\PNG 格式!');
      }
      if (!isLt4M) {
        this.$message.error('上传头像图片大小不能超过 4MB!');
      }
      return isType && isLt4M;
    },
    updateInfo() {
       userApi.updateInfo(this.RestInfo).then(response => {
        this.fetchData()
      })
    },
    updatePwd(){
      this.$refs.pwdRef.validate(valid => {
        if (valid) {
          userApi.updatePassword(this.ResetForm).then(response => {
            this.$message({
              message: '修改成功',
              type: 'sucess'
            })
      })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    }
  }
}
